#include "GameLayer.h"

GameLayer::GameLayer(void)
{
	sGlobal->gameLayer = this;
}


GameLayer::~GameLayer(void)
{
	this->unscheduleAllSelectors();
}



// on "init" you need to initialize your instance
bool GameLayer::init()
{
    bool bRet = false;
    do 
    {
        //////////////////////////////////////////////////////////////////////////
        // super init first
        //////////////////////////////////////////////////////////////////////////
		CC_BREAK_IF(! CCLayer::init());

		GameMap::create("mota01.tmx");
		addChild(sGlobal->gameMap);

		Hero::create();
		sGlobal->hero->setPosition(sGlobal->gameMap->Tile2Pos(ccp(1,11)));
		addChild(sGlobal->hero);

		schedule(schedule_selector(GameLayer::updateSceneScroll));
        bRet = true;
    } while (0);

    return bRet;
}

void GameLayer::setSceneScrollPostion(CCPoint pos)
{
	CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
	CCSize mapSize = CCSize(sGlobal->gameMap->getMapSize().width*sGlobal->gameMap->getTileSize().width,
		sGlobal->gameMap->getMapSize().height*sGlobal->gameMap->getTileSize().height);

	float x = screenSize.width/2.0f;
	float y = screenSize.height/2.0f;
	if ( mapSize.width > screenSize.width)
	{
		x = MAX(pos.x, screenSize.width/2.0f);
		x = MIN( x, mapSize.width - screenSize.width/2.0f);
	}
	if ( mapSize.height > screenSize.height)
	{
		y = MAX(pos.y, screenSize.height/2.0f);
		y = MIN( y, mapSize.height - screenSize.height/2.0f);
	}

	CCPoint heroPos = ccp(x,y);
	CCPoint screenCenter = ccp( screenSize.width/2.0f, screenSize.height/2.0f);
	CCPoint scrScrollPos = ccpSub( screenCenter, heroPos);

	this->setPosition( scrScrollPos);
	CCLog("%f,%f",scrScrollPos.x,scrScrollPos,y);
}

void GameLayer::updateSceneScroll(float dt)
{
	if(sGlobal->hero->isHeroMoving)
	{
		setSceneScrollPostion(sGlobal->hero->getPosition());
	}
}

void GameLayer::showTip(const char *tip, CCPoint startPos)
{
	CCLabelTTF *tipLabel = CCLabelTTF::create(tip, "Arial", 20);
	tipLabel->setPosition(startPos);
	this->addChild(tipLabel, kZTip, kZTip);

	CCAction *act = CCSequence::create(
		CCMoveBy::create(0.5f, ccp(0,32)),
		CCDelayTime::create(0.5f),
		CCFadeOut::create(0.2f),
		CCCallFuncN::create(this, callfuncN_selector(GameLayer::onShowTipDone)),
		NULL);
	tipLabel->runAction(act);
}


void GameLayer::onShowTipDone(CCNode *pSender)
{
	this->getChildByTag(kZTip)->removeFromParentAndCleanup(true);
}


